﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Browsers;
using ProgNetComponentsDx.Data;
using ProgNetComponents.Data.SqlCe;

namespace BuildHelper.Setup.OptionsTabs
{
    public partial class OptionsTabsForm : MyBaseSqlCeGridForm
    {
        public OptionsTabsForm()
        {
            InitializeComponent();
        }

        protected override bool ValidateAll()
        {
            return base.ValidateAll() && this.optionsTabsDataSet.STP_OPCJE_TABS.ValidateColUnique("STP_OPT_LOKALIZACJA", "Lokalizacja powinna być unikalna") &&
                this.optionsTabsDataSet.STP_OPCJE_TABS.ValidateColUnique("STP_OPT_TAB", "Tab powinien być unikalny");
        }

        public static void UpdateLocalizations()
        {
            DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.OptionsTabs).GetChanges();
            if (dt != null)
            {
                OptionsTabsDataSet ds = new OptionsTabsDataSet();
                foreach (DataRow r in dt.Rows)
                {
                    ds.STP_OPCJE_TABS.AddSTP_OPCJE_TABSRow(r["STP_OPT_TAB"].AsString(), r["STP_OPT_LOKALIZACJA"].AsString());
                }
                SqlCeDataManager m = new SqlCeDataManager();
                m.AddTableDef(ds.STP_OPCJE_TABS, "SELECT * FROM STP_OPCJE_TABS");
                m.AutoLogExceptions = true;
                if (m.UpdateTable(ds.STP_OPCJE_TABS))
                {
                    BrowserCache.RefreshCacheForTable("STP_OPCJE_TABS");
                }

                m.Dispose();
            }
        }
        private ProgNetComponentsDx.Forms.FormBackGroundWorkSingleThread searchForm = null;

        private void bbiSzukaj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var browser = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Setup.BranczeAktywne);
            
            var res = browser.ShowDialog();
            if (res.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                DataRow r = browser.GetRowForValue(res.Value);
                if (r != null)
                {
                    searchForm = new ProgNetComponentsDx.Forms.FormBackGroundWorkSingleThread();
                    searchForm.BackgroundControl.ProgressType = ProgNetComponentsDx.Forms.ProgressType.Merque;
                    searchForm.BackgroundControl.LabelText = "Szukanie lokalizacji";
                    
                    searchForm.DoWork += new DoWorkEventHandler(searchForm_DoWork);
                    searchForm.RunWorkerCompleted += new RunWorkerCompletedEventHandler(searchForm_RunWorkerCompleted);
                    searchForm.Argument = r;
                    searchForm.ShowDialog();
                }
            }
        }

        void searchForm_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            searchForm.Close();
            searchForm.Dispose();
        }

        void searchForm_DoWork(object sender, DoWorkEventArgs e)
        {
            DataRow r = e.Argument as DataRow;
            string katalog = r["STP_BR_KATALOG"].AsString();
            string update_configs = katalog.TrimEnd('\\', '/') + @"\nd_src\gene\apps\gcm\src\aix\dbdes\update_configs.sql";
            string update_config_names = katalog.TrimEnd('\\', '/') + @"\nd_src\gene\apps\gcm\src\aix\dbdes\update_config_names.sql";
            try
            {
                Dictionary<string, string> optionsLocations = new Dictionary<string, string>();
                Dictionary<string, string> optionsTabs = new Dictionary<string, string>();

                string update_configsStr = update_configs.ReadFile();
                string update_config_namesStr = update_config_names.ReadFile();
                string namesMask = "INSERT INTO ga_config_names\\(code, name, location\\) VALUES\\( '(.*?)', .*, '(.*?)'\\);".Replace(" ", "\\s*");
                string configMask = "update_configs \\('(.*?)', .*, .*, .*, .*, '(.*?)' \\);".Replace(" ", "\\s*");

                List<Dictionary<int, string>> dicNames = update_config_namesStr.GetMatches(namesMask, new int[] { 1, 2 });
                List<Dictionary<int, string>> dicConfigs = update_configsStr.GetMatches(configMask, new int[] { 1, 2 });

                foreach (Dictionary<int, string> d in dicNames)
                {
                    if (!optionsLocations.ContainsKey(d[1].Trim()))
                        optionsLocations.Add(d[1].Trim(), d[2].Trim());
                }
                foreach (Dictionary<int, string> d in dicConfigs)
                {
                    if (!optionsTabs.ContainsKey(d[1].Trim()))
                        optionsTabs.Add(d[1].Trim(), d[2].Trim());
                }
                if (searchForm.BackgroundControl.IsCanceling)
                    return;
                searchForm.BackgroundControl.MaxProgress = optionsTabs.Count;

                searchForm.BackgroundControl.ProgressType = ProgNetComponentsDx.Forms.ProgressType.Percentage;
                string tab, opcja, local;
                
                foreach (KeyValuePair<string, string> kvp in optionsTabs)
                {
                    if (searchForm.BackgroundControl.IsCanceling)
                        return;
                    searchForm.BackgroundControl.Progress++;
                    tab = kvp.Value;
                    opcja = kvp.Key;
                    if (optionsLocations.ContainsKey(opcja))
                    {
                        local = optionsLocations[opcja];
                        if (tab.IsNotNull() && local.IsNotNull())
                            AddRow(tab, local);
                    }
                }
            }
            catch { }
        }
        private void AddRow(string tab, string local)
        {
            string query = "STP_OPT_TAB = {0} OR STP_OPT_LOKALIZACJA  = {1}";
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, string>(AddRow), tab, local);
                return;
            }
            if (optionsTabsDataSet.STP_OPCJE_TABS.SelectFirstRow(query.XFormat(tab.EscapeSql(), local.EscapeSql())) == null)
            optionsTabsDataSet.STP_OPCJE_TABS.AddSTP_OPCJE_TABSRow(tab, local);
        }

    }
}
